package main

// net/http client

import (
	"fmt"
	"io/ioutil"
	"net/http"
	"net/url"
)

// 共用一个client适用于请求很频繁
var (
	tr = &http.Transport{
	DisableKeepAlives: false,
}
	client = http.Client{
	Transport: tr,
	}
)
func main(){
	//res, err := http.Get("http://127.0.0.1:9090/xxx/?name=yuan&age=18")
	//if err != nil{
	//	fmt.Printf("get url failed, err: %v\n", err)
	//	return
	//}
	data := url.Values{}	// url values
	urlObj, err := url.Parse("http://127.0.0.1:9090/xxx/")
	data.Set("name","天空")
	data.Set("age","18")
	queryStr := data.Encode()	// URL encode之后的URL
	fmt.Println(queryStr)
	urlObj.RawQuery = queryStr
	req, err := http.NewRequest("GET", urlObj.String(), nil)
	//res, err := http.DefaultClient.Do(req)
	//if err != nil{
	//	fmt.Printf("get url failed, err: %v\n", err)
	//	return
	//}

	// 适用于请求不是特别频繁,用完就关闭该连接
	// 禁用keepAlive的client
	//tr := &http.Transport{
	//	DisableKeepAlives: true,
	//}
	//client := http.Client{
	//	Transport: tr,
	//}
	res, err := client.Do(req)
	if err != nil{
		fmt.Printf("get url failed, err: %v\n", err)
	}
	defer res.Body.Close() 	// 关闭链接
	// 发请求

	// 从res中把服务端返回的数据读出来
	//res.Body.Read()

	b, err := ioutil.ReadAll(res.Body)
	if err != nil{
		fmt.Printf("read res.Body failed, err: %v\n", err)
		return
	}
	fmt.Println(string(b))
}